import jQuery from 'jquery';

jQuery.prototype.val = function (base) {
    return function () {
        var tid = jQuery(this).attr("id");
        var isSetting = arguments.length > 0, val = isSetting ? arguments[0] : null;

        //调用jq原方法
        if (isSetting && typeof(base) == "function") {
            base.call(this, val);
        } else {
            if (__judgeBelFormField(tid)) {
                //获取redux中的值
                return window.WfForm.getFieldValue(tid);
            }
            return base.call(this);
        }

        if (__judgeBelFormField(tid)) {
            //更新redux的值
            window.WfForm.changeFieldValue(tid, {
                value: val
            });
        }
        return this;
    }
}(jQuery.prototype.val);//原方法作为参数传入

jQuery.prototype.html = function (base) {
    return function () {
        var tid = this.attr("id");
        var isSetting = arguments.length > 0, htmlStr = isSetting ? arguments[0] : null;

        //调用jq原方法
        if (isSetting && typeof(base) == "function") {
            base.call(this, htmlStr);
            if (!!tid && tid.length > 8 && tid.substring(tid.length - 4) === "span") {
	            var fieldMark = tid.substring(0, tid.length - 4);
	            var fieldObj = jQuery("#"+fieldMark);
	            if(fieldObj.length > 0 && __judgeBelFormField(fieldMark)){
		            window.WfForm.changeFieldValue(fieldMark, {
		                value: fieldObj.val(),
		                showhtml: htmlStr
		            });
	            }
	        }
        } else {
            return base.call(this);
        }
        return this;
    }
}(jQuery.prototype.html);//原方法作为参数传入


/**
 * 严格判断DOM对象是否是表单字段
 */
function __judgeBelFormField(tid){
	var bel = false;
	if(!!tid && new RegExp("^field\\d+(_\\d+)?$").test(tid) && typeof(window.WfForm.getFieldInfo) === "function"){
		var fieldid = tid.indexOf("_")>-1 ? tid.substring(5, tid.indexOf("_")) : tid.substring(5);
		if(window.WfForm.getFieldInfo(fieldid) !== null)
			bel = true;	
	}
	return bel;
}